package com.lyf.baoxian.fragment;

import android.support.v4.app.Fragment;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by liuyafei on 2016/8/24.
 * 管理所有的Fragment，获取Fragment只能通过这个类去构造
 */
public class FragmentInstanceManager {
    private FragmentInstanceManager() {
    }

    private static FragmentInstanceManager sInstance = new FragmentInstanceManager();

    /**
     * 获取实例
     * @return
     */
    public static FragmentInstanceManager getInstance(){
        return sInstance;
    }

    private Map<String,Fragment> mFragments = new HashMap<String, Fragment>();
    /**
     * 提供外部方法去获取Fragment
     */
    public Fragment getFragment(Class<? extends Fragment> clazz ){
        //获取当前的类名
        String key = clazz.getSimpleName();
        //根据类名获取对应的Fragment
        Fragment fragment = mFragments.get(key);
        //当Fragment为空的时候
        if (fragment == null){
            //保证线程的安全，同步代码块中只允许有一个线程
            synchronized (FragmentInstanceManager.class){
                try{
                    if (fragment == null){
                        //获取当前类的实例
                        fragment = clazz.newInstance();
                        //放进集合中
                        mFragments.put(key,fragment);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    throw new RuntimeException(e.getMessage());
                }
            }
        }
        return fragment;
    }
}
